//
//  CLLabel.m
//  CLBrowser
//
//  Created by 梁慧聪 on 2022/10/31.
//

#import "CLLabel.h"

@implementation CLLabel

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (!self) return nil;

    // set inital value via IVAR so the setter isn't called
    _verticalAlignment = CLVerticalAlignmentMiddle;

    return self;
}

- (void) setVerticalAlignment:(CLVerticalAlignment)value {
    _verticalAlignment = value;
    [self setNeedsDisplay];
}

// align text block according to vertical alignment settings
- (CGRect)textRectForBounds:(CGRect)bounds
    limitedToNumberOfLines:(NSInteger)numberOfLines {
   CGRect rect = [super textRectForBounds:bounds
                   limitedToNumberOfLines:numberOfLines];
    CGRect result;
    switch (_verticalAlignment)
    {
       case CLVerticalAlignmentTop:
          result = CGRectMake(bounds.origin.x, bounds.origin.y, rect.size.width, rect.size.height);
           break;

       case CLVerticalAlignmentMiddle:
          result = CGRectMake(bounds.origin.x,
                    bounds.origin.y + (bounds.size.height - rect.size.height) / 2,
                    rect.size.width, rect.size.height);
          break;

       case CLVerticalAlignmentBottom:
          result = CGRectMake(bounds.origin.x,
                    bounds.origin.y + (bounds.size.height - rect.size.height),
                    rect.size.width, rect.size.height);
          break;

       default:
          result = bounds;
          break;
    }
    return result;
}

- (void)drawTextInRect:(CGRect)rect {
    CGRect r = [self textRectForBounds:rect
                limitedToNumberOfLines:self.numberOfLines];
    [super drawTextInRect:r];
}

@end
